<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'withdrawals';
	protected $_ci;
	public function __construct()
	{
		parent::__construct();
		$this->_ci = &get_instance();
		// Load all the required classes
		$this->load->library('form_validation');
		$this->load->model('escort_withdrawals_m');
		$this->load->model('groups_m');
		$this->load->model('users_m');
		$this->load->model('escort_user_roles_n_benefits_m');
		
		$this->lang->load('withdrawal');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'user_id',
				'label' => 'lang:escort_withdrawal_user_label',
				'rules' => 'trim|max_length[255]|required'
			),
			array(
				'field' => 'user_type',
				'label' => 'lang:escort_withdrawal_user_type_label'
			),
			array(
				'field'	=> 'created_date',
				'label'	=> 'lang:escort_withdrawal_date_label',
				'rules' => 'trim|max_length[255]|required'
			),
			array(
				'field' => 'money',
				'label' => 'lang:escort_withdrawal_money_label',
				'rules' => 'trim|max_length[255]|numeric'
			),
			array(
				'field' => 'status',
				'label' => 'lang:escort_withdrawal_status_label',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'paid_date',
				'label' => 'lang:escort_withdrawal_paid_date_label',
				'rules' => 'trim'
			),
			array(
				'field' => 'payment_method_id',
				'label' => 'lang:escort_withdrawal_payment_method_label',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'payment_method_commentaries',
				'label' => 'lang:escort_withdrawal_payment_method_commentaries_label',
				'rules' => 'trim'
			),
		);

		$this->data->userList = array();
		$users = $this->escort_user_roles_n_benefits_m->get_all();
		if($users){
			foreach ($users as $user) {
				$this->data->userList[$user->id.'_'.WITHDRAWAL_USER_BACKEND] = $user->username;
			}
		}
		$agents = $this->_ci->user_entity->getUserListByType(array(), array(USER_TYPE_AGENT));
		if($agents){
			foreach ($agents as $agent){
				$this->data->userList[$agent->id.'_'.WITHDRAWAL_USER_AGENT] = $agent->username;
			}
		}
		
		$this->data->statusList = array(
			'yes'	=> 'Yes',
			'no'	=> 'No',
			'awaiting' => lang('escort_withdrawal_awaiting_label')
		);

		$this->data->paymentMeothodList = array();
		$paymentMethods = $this->_ci->payment_method_entity->getPaymentMethodListByLanguage($this->_ci->escort_setting_entity->getDefaultLanguageId());
		if($paymentMethods){
			foreach ($paymentMethods as $paymentMethod){
				$this->data->paymentMeothodList[$paymentMethod->id] = $paymentMethod->method; 		
			}
		}
		
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
		->append_metadata(js('escort.withdrawal.js', 'be_withdrawal'))
		->append_metadata(css('escort.withdrawal.css', 'be_withdrawal'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		
		$base_where = array();
		$base_where = $this->input->post('f_company') ? $base_where + array('company' => $this->input->post('f_company')) : $base_where;
		$base_where = $this->input->post('f_from') ? $base_where + array('from' => $this->input->post('f_from')) : $base_where;
		$base_where = $this->input->post('f_to') ? $base_where + array('to' => $this->input->post('f_to')) : $base_where;
		// Create pagination links
		$total_rows = $this->_ci->withdrawal_entity->count($base_where);
		$pagination = create_pagination('admin/be_withdrawal/index', $total_rows);
		// Using this data, get the relevant results
		$withdrawals = $this->_ci->withdrawal_entity->getList($pagination['limit'], $base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
		->title($this->module_details['name'])
		->append_metadata(js('admin/filter.js'))
		->set('pagination', $pagination)
		->set('withdrawals', $withdrawals);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}

	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);

		if ($this->form_validation->run())
		{
			$userString	= $this->input->post('user_id');
			$userDataArr = explode('_', $userString);
			$userId = $userDataArr[0];
			$userType = $userDataArr[1];
			if($userType == WITHDRAWAL_USER_AGENT){
				$user = $this->_ci->user_entity->init('id',$userId);
				$username = $user->getUserName();
				$name = $user->getName();
			}else{
				$user = $this->escort_user_roles_n_benefits_m->get($userId);
				$username = $user->username;
				$name = $user->name;
			}
			
			$id = $this->escort_withdrawals_m->insert(array(
				'user_id'	=> $userId,
				'user_type'	=> $userType,
				'user_username'	=> $username,
				'user_name'	=>$name,
				'created_date'	=> strtotime($this->input->post('created_date')),
				'money'	=> $this->input->post('money'),
				'status'	=> $this->input->post('status'),
				//'paid_status'	=> $this->input->post('paid_status'),
				'paid_date'	=> strtotime($this->input->post('paid_date')),	
				'payment_method_id'	=> $this->input->post('payment_method_id'),
				'payment_method_commentaries'	=> $this->input->post('payment_method_commentaries')
			));
			if ($id)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_withdrawal_add_success'), $username));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_withdrawal_add_error'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_withdrawal') : redirect('admin/be_withdrawal/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$withdrawal->$field['field'] = set_value($field['field']);
			}
		}
		
		if($withdrawal->created_date == null || $withdrawal->created_date == ''){
			$withdrawal->created_date = time();
		}
		if($withdrawal->paid_date == null || $withdrawal->paid_date == ''){
			$withdrawal->paid_date = 0;
		}

		$this->template
		->title($this->module_details['name'], lang('escort_withdrawal_add_title'))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('withdrawal', $withdrawal)
		->build('admin/form', $this->data);
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/be_withdrawal');
		$withdrawal = $this->escort_withdrawals_m->get($id);
		$withdrawal OR redirect('admin/be_withdrawal');
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run())
		{
			$userString	= $this->input->post('user_id');
			$userDataArr = explode('_', $userString);
			$userId = $userDataArr[0];
			$userType = $userDataArr[1];
			if($userType == WITHDRAWAL_USER_AGENT){
				$user = $this->_ci->user_entity->init('id',$userId);
				$username = $user->getUserName();
				$name = $user->getName();
			}else{
				$user = $this->escort_user_roles_n_benefits_m->get($userId);
				$username = $user->username;
				$name = $user->name;
			}
			$result = $this->escort_withdrawals_m->update($id, array(
					'user_id'	=> $userId,
					'user_type'	=> $userType,
					'user_username'	=> $username,
					'user_name'	=>$name,
					'created_date'	=> strtotime($this->input->post('created_date')),
					'money'	=> $this->input->post('money'),
					'status'	=> $this->input->post('status'),
					//'paid_status'	=> $this->input->post('paid_status'),
					'paid_date'	=> strtotime($this->input->post('paid_date')),	
					'payment_method_id'	=> $this->input->post('payment_method_id'),
					'payment_method_commentaries'	=> $this->input->post('payment_method_commentaries')
			));

			if ($result)
			{
				$this->session->set_flashdata(array('success' => sprintf(lang('escort_withdrawal_edit_success'), $username)));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_withdrawal_edit_error'));
			}

			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_withdrawal') : redirect('admin/be_withdrawal/edit/' . $id);
		}

		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$withdrawal->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
		->title($this->module_details['name'], lang('escort_withdrawal_edit_title'))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('withdrawal', $withdrawal)
		->build('admin/form');
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');

		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$withdrawalIds = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($withdrawal = $this->escort_withdrawals_m->get($id))
				{
					$this->escort_withdrawals_m->delete($id);

					// Wipe cache for this model, the content has changed
					$this->pyrocache->delete('escort_withdrawals_m');
					$withdrawalIds[] = $withdrawal->id;
				}
			}
		}

		// Some pages have been deleted
		if ( ! empty($withdrawalIds))
		{
			// Only deleting one page
			if (count($withdrawalIds) == 1)
			{
				$this->session->set_flashdata('success', $this->lang->line('escort_withdrawal_delete_success'));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', $this->lang->line('escort_withdrawal_mass_delete_success'));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_withdrawal_delete_error'));
		}

		redirect('admin/be_withdrawal');
	}
	
	public function export_whole_list(){
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: attachment; filename=" . date("Y-m-d").".csv");
		echo lang('escort_withdrawal_id_label').',';
		echo lang('escort_withdrawal_user_label').',';
		echo lang('escort_withdrawal_date_label').',';
		echo lang('escort_withdrawal_status_label').',';
		echo lang('escort_withdrawal_money_label').',';
		echo lang('escort_withdrawal_payment_date_label').',';
		echo "\r\n";
		$withdrawals = $this->escort_withdrawals_m->order_by('created_date', 'desc')->get_all();
		if($withdrawals){
			foreach ($withdrawals as $withdrawal){
				echo $withdrawal->id.',';
				echo $withdrawal->user_username.',';
				echo format_date($withdrawal->created_date).',';
				if($withdrawal->status == 'no'){
					if($withdrawal->created_date < time()){
						echo lang('escort_withdrawal_debt_label');
					}else{
						echo lang('escort_withdrawal_pending_label');
					}
				}else if($withdrawal->status == 'awaiting'){
					echo lang('escort_withdrawal_awaiting_label');
				}else{
					echo $withdrawal->status;
				}
				echo ',';
				echo $withdrawal->money.',';
				echo format_date($withdrawal->paid_date).',';
				echo "\r\n";
			}
		}
		
	}
	public function mark_as_paid($id=0){
		$id OR redirect('admin/be_withdrawal');
		$withdrawal = $this->escort_withdrawals_m->get($id);
		$withdrawal OR redirect('admin/be_withdrawal');
		$result = $this->escort_withdrawals_m->update($id, array(
			'status'	=> 'yes',
			'paid_date' => time()
		));
		if($result){
			$this->session->set_flashdata('success', $this->lang->line('escort_withdrawal_mark_as_paid_success'));
		}else{
			$this->session->set_flashdata('notice', $this->lang->line('escort_withdrawal_mark_as_paid_error'));
		}
		redirect('admin/be_withdrawal');
	}
}
